package chat.user.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import chat.user.domain.User;
import chat.user.service.UserException;
import chat.user.service.UserService;

/**
 * Servlet implementation class UserServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	UserService userService = new UserService();
	

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//退出
		User user = (User)request.getSession().getAttribute("session_user");
		userService.updateIsOnline(user.getId(),0);
		request.getSession().invalidate();
		response.sendRedirect("/chat/view/login.jsp");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("content-type","text/html;charset=UTF-8");
		
		User form = new User();
		form.setUsername(request.getParameter("username"));
		form.setPassword(request.getParameter("password"));
		
		try
		{
			User user = userService.login(form);
			
			request.getSession().setAttribute("session_user",user);
			userService.updateIsOnline(user.getId(),1);
			response.sendRedirect("/chat/view/chatroom/chatroom.jsp");
		}
		catch(UserException e)
		{
			request.setAttribute("msg",e.getMessage());
			request.getRequestDispatcher("/view/login.jsp").forward(request, response);
		}
	}

}
